package sms

import (
	"encoding/json"
	"gohub/pkg/logger"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)

// Aliyun 实现 sms.Driver interface
type Aliyun struct{}

// Send 实现 sms.Driver interface 的 Send 方法
func (s *Aliyun) Send(phone string, message Message, config map[string]string) bool {

	smsClient, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", config["access_key_id"], config["access_key_secret"])
	if err != nil {
		logger.ErrorString("短信[阿里云]", "NewClientWithAccessKey", err.Error())
		return false
	}

	logger.DebugJSON("短信[阿里云]", "配置信息", config)

	// 创建请求
	request := dysmsapi.CreateSendSmsRequest()
	// request属性设置
	request.Scheme = "https"
	request.SignName = config["sign_name"]
	request.TemplateCode = message.Template
	request.PhoneNumbers = phone

	// 使用json字符串发送验证码
	par, err := json.Marshal(map[string]interface{}{
		"code": "12345",
	})

	// 设置验证码
	request.TemplateParam = string(par)

	response, err := smsClient.SendSms(request)
	if err != nil {
		logger.ErrorString("短信[阿里云]", "发信失败", err.Error())
		return false
	}

	// 检查返回结果，并判断发生状态
	if response.Code != "OK" {
		return false
	}
	return true
}
